package service.impl;

import dao.IUsersDao;
import dao.impl.UserDaoImpl;
import org.apache.commons.dbutils.ResultSetHandler;
import pojo.User;
import service.IUserService;
import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements IUserService {
    private final IUsersDao usersDao = new UserDaoImpl();

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean insertUser(User user) {
        return usersDao.insertUser(user);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<User> queryAllUser() {
        return usersDao.queryAllUser();
    }

    /**
     * 查询所有用户名
     *
     * @return List<String>
     */
    @Override
    public List<String> queryAllUsername() {
        List<String> results = new ArrayList<>();
        for (User user : usersDao.queryAllUser()) {
            results.add(user.getUsername());
        }
        return results;
    }


    /**
     * 用户名判重
     *
     * @return
     */
    @Override
    public boolean isUsernameExists(String username) {
        return queryAllUsername().contains(username);
    }

    /**
     * 根据用户名和密码判断用户是否存在
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean isUserExistsByUsernameAndPassword(String username, String password) {
        return usersDao.queryUserByUsernameAndPassword(username, password) != null;
    }

    /**
     * 根据用户名查找用户id
     *
     * @param username
     * @return
     */
    @Override
    public int queryIdByUsername(String username) {
        return usersDao.queryUserByUsername(username).getId();
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User queryUserById(int id) {
        return usersDao.queryUserById(id);
    }

    /**
     * 根据用户名和密码判断是否为管理员
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean isAdminByUsernameAndPassword(String username, String password) {
        return usersDao.queryUserByUsernameAndPassword(username, password).isAdmin();
    }

}
